package yunplus.io.hchome.display.video;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;

import com.company.PlaySDK.Constants;
import com.company.PlaySDK.IPlaySDK;
import com.company.PlaySDK.IPlaySDKCallBack;

import java.io.FileInputStream;

import static android.R.attr.port;


/**
 * Created by dxq on 2017/6/25.
 */

public class VideoThread extends Thread {
    private static final String TAG = VideoThread.class.getSimpleName();

    private Handler mHandler;
    private final Object mSync = new Object();
    DeviceInfo mDf;
    SurfaceView mSurfaceView;
    int mWidth;
    int mHeight;

    public static int MODE_FILE = 0x01;
    public static int MODE_STREAM = 0x02;
    private int mMode = MODE_STREAM;
    private String mCurrFile;

    public void setDeviceInfo(DeviceInfo df) {
        mDf = df;
    }

    public void setSurface(SurfaceView sv) {
        mSurfaceView = sv;
    }

    public void changeSurface(int width, int height) {
        mWidth = width;
        mHeight = height;
        getHandler().sendEmptyMessage(Const.RequestType.SURFACEVIEW_CHANGED);
    }

    public void startPlay() {
        getHandler().sendEmptyMessage(Const.RequestType.START_PLAY);
    }

    public void pausePlay(){

    }

    public void resumePlay() {

    }

    public void stopPlay() {
        getHandler().sendEmptyMessage(Const.RequestType.STOP_PLAY);
    }

    public void fastForward() {

    }

    public void rewind() {

    }

    public void stopFFOrRW() {

    }

    public void run() {
        Looper.prepare();
        synchronized (mSync) {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.d("TAG", "handleMessage---" + msg);
                    switch (msg.what) {
                        case Const.RequestType.INIT_SURFACE:
                            IPlaySDK.InitSurface(mDf.port, mSurfaceView);
                            break;
                        case Const.RequestType.UINIT_SURFACE:
                            IPlaySDK.UinitSurface(mDf.port);
                            break;

                        case Const.RequestType.SURFACEVIEW_CHANGED:
                            IPlaySDK.PLAYViewResolutionChanged(mDf.port, mWidth, mHeight, 0);
                            break;
                        case Const.RequestType.START_PLAY:
                            startPlaySDK();
                            break;
                        case Const.RequestType.STOP_PLAY:
                            stopPlaySDK();
                            break;
                    }
                }
            };
            mSync.notifyAll();
        }
        Looper.loop();
    }

    private Handler getHandler() {
        synchronized (mSync) {
            if (mHandler == null) {
                try {
                    mSync.wait();
                } catch (InterruptedException e) {
                }
            }
            return mHandler;
        }
    }

    public void exit() {
        getHandler().post(new Runnable() {
            public void run() {
                Looper.myLooper().quit();
            }
        });
    }



    private void startPlaySDK() {
        int retValue = 0;
        if(mMode == MODE_FILE) {
            long lUsrdata = 0;
            retValue = IPlaySDK.PLAYSetFileEndCallBack(port, new PlayEndCallBack(), lUsrdata);
            if(0 == retValue) {
                Log.d(TAG, "PLAYSetFileEndCallBack Failed.");
                return;
            }
            retValue = IPlaySDK.PLAYOpenFile(port, mCurrFile);
            if(0 == retValue) {
                Log.d(TAG, "PLAYOpenFile Failed.");
                return;
            }
        } else {
            IPlaySDK.PLAYSetStreamOpenMode(port, Constants.STREAME_FILE);
            retValue = IPlaySDK.PLAYOpenStream(port, null, 0, 5*1024*1024);
            if(0 == retValue) {
                Log.d(TAG, "PLAYOpenStream Failed.");
                return;
            }
        }

        retValue = IPlaySDK.PLAYPlay(port, mSurfaceView);
        if(0 == retValue) {
            Log.d(TAG, "PLAYPlay Failed.");
            return;
        }
        retValue = IPlaySDK.PLAYPlaySound(port);
        if(0 == retValue) {
            Log.d(TAG, "PLAYPlaySound Failed.");
        }

//        //sound capture test.
//        int m_nBitPerSample = 16;
//        int m_nSamplePerSecond = 8000;
//        int lSampleLen = m_nBitPerSample*m_nSamplePerSecond/8;
//        TestAudioRecord m_audiorecordcallback = new TestAudioRecord();
//        retValue = IPlaySDK.PLAYOpenAudioRecord(m_audiorecordcallback,m_nBitPerSample,m_nSamplePerSecond, lSampleLen, 0);
//        if(0 == retValue) {
//            Log.d(TAG, "PLAYOpenAudioRecord Failed.");
//        }

        if(mMode == MODE_STREAM) {
            try {
                FileInputStream fis = new FileInputStream(mCurrFile);
                int readsize = 1024*1024;
                byte[] buffer = new byte[readsize];
                int readlen = 0;
                int ret = 0;
                while((readlen = fis.read(buffer)) != -1) {
                    ret = IPlaySDK.PLAYInputData(port, buffer, readlen);
                    if(ret == 0) {
                        Log.d("[playsdk]PLAYInputData", "Failed.");
                    }
                }
                fis.close();
            } catch(Exception e) {
            }
        }
    }

    private class PlayEndCallBack implements IPlaySDKCallBack.fpFileEndCBFun {
        @Override
        public void invoke(int nPort, long pUserData) {
            try {
                Message msg = new Message();
                msg.what = 2;
                stopPlay();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void stopPlaySDK()
    {
        IPlaySDK.PLAYStopSound();
        //clear Screen
        IPlaySDK.PLAYCleanScreen(port, 0/*red*/, 0/*green*/, 0/*blue*/, 1/*alpha*/, 0);
        IPlaySDK.PLAYStop(port);
        IPlaySDK.PLAYCloseAudioRecord();

        if(mMode == MODE_FILE) {
            IPlaySDK.PLAYCloseFile(port);
        } else {
            IPlaySDK.PLAYCloseStream(port);
        }
    }

}
